import React, { Component } from 'react';
import { ScrollView, View, StyleSheet, Text, Alert } from 'react-native';
import { px2dp } from 'bee/utils/px2dp';
import { sizes, colors } from 'bee/themes';
import ResetPasswordItem from 'bee/components/ResetPassword';
import codeStrength from 'bee/containers/ResetPassword/Calculate';
import { Icon, Names } from 'bee/components/Icon';
import { SimpleBtn } from 'bee/components/Buttons';

// @flow
type props = {
  navigation: object,
};

export default class ResetPassword extends Component<props> {
  constructor() {
    super();

    // create a ref to store the textInput DOM element
    this.originalPassword = React.createRef();
    this.newPassword = React.createRef();

    this.state = {
      // 错误提示标记
      errorFlag: false,
      // 错误提示信息
      errMessage: null,
      // 密码强度
      passwordStength: null,
      // 新密码
      newPassword: null,
      // 原登录密码
      originalPassword: null,
      // 已输入原始登陆密码标记
      haveOriginalPassword: true,
      // 已输入新登录密码标记
      haveNewPassword: true,
    };
  }

  // focusTextInput(component) {
  //   console.log(component);
  //   // Explicitly focus the text input using the raw DOM API
  //   // Note: we're accessing "current" to get the DOM node
  //   component.current.focus();
  // }

  render() {
    const { params } = this.props.navigation.state;
    return (
      <ScrollView>
        <Text style={styles.title}>
          您正在为手机号码 {params.phone} 修改登录密码
        </Text>
        <ResetPasswordItem
          reference={this.originalPassword}
          title="原登录密码："
          placeholder="请输入原登录密码"
          onChangeText={text => {
            this.setState({
              originalPassword: text,
              haveOriginalPassword: true,
            });
          }}
        />
        {this.state.haveOriginalPassword ? null : (
          <View style={styles.messageBox}>
            <Icon name={Names.zhuyi} size={sizes.f1} color={colors['1003']} />
            <Text style={styles.errMessage}>请您先输入原登陆密码</Text>
          </View>
        )}
        <ResetPasswordItem
          reference={this.newPassword}
          style={styles.blank}
          title="新登录密码："
          placeholder="请输入新登录密码"
          onFocus={() => {
            if (
              this.state.originalPassword === '' ||
              this.state.originalPassword === null
            ) {
              // console.log('shima');
              this.setState({
                haveOriginalPassword: false,
              });
              this.originalPassword.current.focus();
            }
          }}
          onChangeText={text => {
            // console.log('text:', text);
            const info = codeStrength(text);
            if (text === '') {
              this.setState({
                passwordStength: codeStrength.Zero,
                haveNewPassword: true,
              });
              return;
            }
            if (info.startsWith('error')) {
              const arr = info.split(':');
              this.setState({
                errorFlag: true,
                passwordStength: arr[0],
                errMessage: arr[1],
                haveNewPassword: true,
              });
            } else {
              this.setState({
                errorFlag: false,
                passwordStength: info,
                newPassword: text,
                haveNewPassword: true,
              });
            }
          }}
          onEndEditing={event => {
            if (this.state.originalPassword === event.nativeEvent.text) {
              Alert.alert('提示', '原登陆密码与新密码不能完全一致，请重新输入');
            }
          }}
        />
        {this.state.errorFlag ? (
          <View style={styles.messageBox}>
            <Icon name={Names.zhuyi} size={sizes.f1} color={colors['1003']} />
            <Text style={styles.errMessage}>{this.state.errMessage}</Text>
          </View>
        ) : null}
        {this.state.haveNewPassword ? null : (
          <View style={styles.messageBox}>
            <Icon name={Names.zhuyi} size={sizes.f1} color={colors['1003']} />
            <Text style={styles.errMessage}>请您先输入新密码</Text>
          </View>
        )}
        <View style={styles.strengthBox}>
          <Text style={styles.strengthText}>密码强度</Text>
          <View style={styles.strengthShowBox}>
            {['弱', '一般', '强', '安全'].map((value, index) => {
              // console.log('passwordStength', this.state.passwordStength);
              let bgc = colors.white;
              // if (this.state.passwordStength !== null) {
              switch (this.state.passwordStength) {
                case codeStrength.Weak:
                  switch (index) {
                    case 0:
                      bgc = colors['1003'];
                      break;
                    default:
                      bgc = colors.white;
                      break;
                  }
                  break;
                case codeStrength.Average:
                  switch (index) {
                    case 0:
                    case 1:
                      bgc = '#FFE153';
                      break;
                    default:
                      bgc = colors.white;
                      break;
                  }
                  break;
                case codeStrength.Strong:
                  switch (index) {
                    case 0:
                    case 1:
                    case 2:
                      bgc = '#8CEA00';
                      break;
                    default:
                      bgc = colors.white;
                      break;
                  }
                  break;
                case codeStrength.Secure:
                  switch (index) {
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                      bgc = '#548C00';
                      break;
                    default:
                      bgc = colors.white;
                      break;
                  }
                  break;
                default:
                  bgc = colors.white;
                  break;
              }
              // }
              return (
                <View key={index} style={styles.littleStrengthShowBox}>
                  <View style={[styles.showColor, { backgroundColor: bgc }]} />
                  <Text style={styles.font}>{value}</Text>
                </View>
              );
            })}
          </View>
        </View>
        <ResetPasswordItem
          title="确认新密码："
          placeholder="请输入密码"
          onFocus={() => {
            if (
              this.state.originalPassword === '' ||
              this.state.originalPassword === null
            ) {
              this.setState({
                haveOriginalPassword: false,
              });
              this.originalPassword.current.focus();
              return;
            }
            if (
              this.state.newPassword === '' ||
              this.state.newPassword === null
            ) {
              this.setState({
                haveNewPassword: false,
              });
              this.newPassword.current.focus();
            }
          }}
          onEndEditing={event =>
            // console.log('event.nativeEvent.text:', event.nativeEvent.text);
            // console.log('this.state.newPassword:', this.state.newPassword);
            this.state.newPassword !== null &&
            this.state.newPassword !== '' &&
            event.nativeEvent.text !== '' &&
            event.nativeEvent.text !== null &&
            event.nativeEvent.text !== this.state.newPassword
              ? Alert.alert('确认密码与新密码不一致请重新输入')
              : null
          }
        />
        <View style={[styles.messageBox, { marginBottom: px2dp(200) }]}>
          <Icon name={Names.zhuyi} size={sizes.f1} color={colors['1003']} />
          <Text style={[styles.errMessage, { color: colors['1101'] }]}>
            请不要向任何人透露您的登录密码
          </Text>
        </View>

        <View style={styles.buttonBox}>
          <SimpleBtn
            text="确认"
            onPress={() => {}}
            bgc={colors['1001']}
            fontColor={colors.white}
          />
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  title: {
    lineHeight: px2dp(63),
    textAlign: 'center',
    fontSize: sizes.f2,
    color: colors['1101'],
    // backgroundColor: 'blue',
  },
  blank: {
    marginTop: px2dp(20),
  },
  strengthBox: {
    height: px2dp(110),
    flexDirection: 'row',
    alignItems: 'center',
  },
  strengthText: {
    marginLeft: px2dp(50),
    fontSize: sizes.f2,
    color: colors['1101'],
  },
  strengthShowBox: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
  },
  littleStrengthShowBox: {
    width: px2dp(100),
    alignItems: 'center',
  },
  showColor: {
    height: px2dp(17),
    width: px2dp(100),
    marginBottom: px2dp(20),
    backgroundColor: colors.white,
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: colors['1104'],
  },
  font: {
    fontSize: sizes.f2,
    color: colors['1101'],
  },
  errMessage: {
    fontSize: sizes.f1,
    color: colors['1003'],
    marginLeft: px2dp(8),
  },
  messageBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(50),
    marginTop: px2dp(16),
    marginBottom: px2dp(20),
  },
  buttonBox: {
    marginHorizontal: px2dp(30),
  },
});
